package com.lipi.mall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.lipi.common.exception.NoStockException;
import com.lipi.common.to.SkuHasStockVO;
import com.lipi.common.to.mq.OrderTO;
import com.lipi.common.to.mq.SeckillOrderTO;
import com.lipi.common.utils.R;
import com.lipi.common.vo.MemberRespVO;
import com.lipi.mall.order.constant.OrderConstant;
import com.lipi.mall.order.entity.OrderItemEntity;
import com.lipi.mall.order.entity.PaymentInfoEntity;
import com.lipi.mall.order.enums.OrderStatusEnum;
import com.lipi.mall.order.feign.CartFeignService;
import com.lipi.mall.order.feign.MemberFeignService;
import com.lipi.mall.order.feign.ProductFeignService;
import com.lipi.mall.order.feign.WareFeignService;
import com.lipi.mall.order.interceptor.LoginUserInterceptor;
import com.lipi.mall.order.service.OrderItemService;
import com.lipi.mall.order.service.PaymentInfoService;
import com.lipi.mall.order.to.OrderCreateTo;
import com.lipi.mall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lipi.common.utils.PageUtils;
import com.lipi.common.utils.Query;

import com.lipi.mall.order.dao.OrderDao;
import com.lipi.mall.order.entity.OrderEntity;
import com.lipi.mall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVO> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVO confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVO vo = new OrderConfirmVO();
        //获取用户的登录信息
        MemberRespVO memberRespVo = LoginUserInterceptor.loginUser.get();

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();


        CompletableFuture<Void> userMemberAddressTask = CompletableFuture.runAsync(() -> {
            //1、查询会员的所有地址信息
            //同步线程上下文
            RequestContextHolder.setRequestAttributes(requestAttributes);

            List<MemberAddressVO> addressList = memberFeignService.getAddress(memberRespVo.getId());
            vo.setAddress(addressList);
        }, executor);

        CompletableFuture<Void> cartItemTask = CompletableFuture.runAsync(() -> {
            //2、查询购物车选中的购物项
            //同步线程上下文
            RequestContextHolder.setRequestAttributes(requestAttributes);

            List<OrderItemVO> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
            vo.setItems(currentUserCartItems);
        }, executor).thenRunAsync(() -> {
            //查询库存信息
            List<OrderItemVO> items = vo.getItems();
            List<Long> collect = items.stream().map(item -> {
                return item.getSkuId();
            }).collect(Collectors.toList());

            R r = wareFeignService.skuHasStock(collect);

            List<SkuHasStockVO> data = r.getData(new TypeReference<List<SkuHasStockVO>>() {
            });

            //转化为map形式
            if (data != null) {
                Map<Long, Boolean> skuStockMap = data.stream().collect(Collectors.toMap((item) -> {
                    return item.getSkuId();
                }, (item) -> {
                    return item.getHasStock();
                }));

                vo.setStocks(skuStockMap);
            }

        });


        //3、查询用户积分
        Integer integration = memberRespVo.getIntegration();
        vo.setIntegration(integration);

        //4、幂等性防重令牌
        String token = UUID.randomUUID().toString().replace("_", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);
        vo.setOrderToken(token);


        //阻塞等待
        CompletableFuture.allOf(userMemberAddressTask, cartItemTask).get();
        return vo;
    }


    @Transactional
    @Override
    public SubmitOrderResponseVO submitOrder(OrderSubmitVO vo) {
        //获取登录的用户信息
        MemberRespVO memberRespVo = LoginUserInterceptor.loginUser.get();
        //传递参数给后续方法使用
        confirmVoThreadLocal.set(vo);
        //构建返回对象
        SubmitOrderResponseVO response = new SubmitOrderResponseVO();
        response.setCode(0);
        // 1、验证令牌
        Long memberId = memberRespVo.getId();

        //使用脚本来校验令牌,0是校验失败,1是校验成功并删除了令牌,这个过程是原子的
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String tokenKey = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberId;
        Long tokenResult = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(tokenKey), vo.getOrderToken());

        if (tokenResult != 1) {
            //验证不通过
            return response;
        }

        //构建订单数据
        OrderCreateTo order = createOrder();

        //2、验价
        BigDecimal payAmount = order.getOrder().getPayAmount();
        BigDecimal payPrice = vo.getPayPrice();
        if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
            //金额对比
            //....
            //TODO 3、保存订单
            saveOrder(order);
            //4、库存锁定。只要有异常回滚订单数据。
            // 订单号，所有订单项（skuId，skuName，num）
            WareSkuLockVO lockVo = new WareSkuLockVO();
            lockVo.setOrderSn(order.getOrder().getOrderSn());
            List<OrderItemVO> locks = order.getOrderItems().stream().map(item -> {
                OrderItemVO itemVo = new OrderItemVO();
                itemVo.setSkuId(item.getSkuId());
                itemVo.setCount(item.getSkuQuantity());
                itemVo.setTitle(item.getSkuName());
                return itemVo;
            }).collect(Collectors.toList());
            lockVo.setLocks(locks);
            //4、远程锁库存
            //库存成功了，但是网络原因超时了，订单回滚，库存不滚。

            //为了保证高并发。库存服务自己回滚。可以发消息给库存服务；
            //库存服务本身也可以使用自动解锁模式  消息
            R r = wareFeignService.orderLockStock(lockVo);
            if (r.getCode() == 0) {
                //锁成功了
                response.setOrder(order.getOrder());

                //TODO 5、远程扣减积分 出异常
                // int i = 10/0; //订单回滚，库存不滚
                //订单创建成功发送消息给MQ
                rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());

                //TODO 6、清除购物车已经下单的商品
                return response;
            } else {
                //锁定失败
                String msg = (String) r.get("msg");
                throw new NoStockException(msg);
            }


        } else {
            response.setCode(2);
            return response;
        }


    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    /**
     * 关闭订单
     *
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询订单状态
        OrderEntity orderEntity = this.getById(entity.getId());
        Integer status = orderEntity.getStatus();
        //只有新建态的订单才可以被关单
        if (status == OrderStatusEnum.CREATE_NEW.getCode()) {
            //防止数据被修改过,只传id和status
            OrderEntity updateEntity = new OrderEntity();
            updateEntity.setId(entity.getId());
            updateEntity.setStatus(OrderStatusEnum.CANCLED.getCode());

            this.updateById(updateEntity);

            //为防止关单消息比库存校验消息慢,导致库存无法正确释放。在关闭订单后,再让库存校验一次
            OrderTO orderTO = new OrderTO();
            BeanUtils.copyProperties(orderEntity, orderTO);

            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTO);
        }
    }


    @Override
    public PayVO getOrderPay(String orderSn) {
        PayVO payVO = new PayVO();
        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);

        //处理bigDecimal类型数值,向上取两位小数
        BigDecimal bigDecimal = orderEntity.getTotalAmount().setScale(2, BigDecimal.ROUND_UP);
        //支付总额,支付宝只支持两位小数
        payVO.setTotal_amount(bigDecimal.toString());
        //订单号
        payVO.setOut_trade_no(orderSn);

        List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderEntity));

        //展示的标题,简单处理只获取第一个
//        payVO.setSubject(orderItemEntities.get(0).getSkuName());


        //展示的消息体
//        payVO.setBody(orderItemEntities.get(0).getSkuAttrsVals());

        payVO.setSubject("test");
        payVO.setBody("test");
        return payVO;
    }

    /**
     * 分页查询当前登录用户的订单列表页数据
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {

        MemberRespVO memberRespVo = LoginUserInterceptor.loginUser.get();

        //分页查询订单主表数据
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                        .eq("member_id", memberRespVo.getId())
                        .orderByDesc("order_sn")
        );

        //为订单主表构建订单项数据
        List<OrderEntity> collect = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> orderItemEntities = orderItemService
                    .list(new QueryWrapper<OrderItemEntity>()
                            .eq("order_sn", order.getOrderSn()));

            order.setItemEntities(orderItemEntities);

            return order;
        }).collect(Collectors.toList());

        page.setRecords(collect);
        return new PageUtils(page);

    }

    /**
     * 支付宝异步回调请求,验签成功后业务方法
     *
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVO vo) {
        // 1、保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());


        paymentInfoService.save(infoEntity);

        //2、修改订单状态为已支付
        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")) {
            //支付成功状态
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTO orderTO) {
        //保存订单信息
        OrderEntity orderEntity = new OrderEntity();

        orderEntity.setOrderSn(orderTO.getOrderSn());
        orderEntity.setMemberId(orderTO.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        BigDecimal multiply = new BigDecimal(String.valueOf(orderTO.getSeckillPrice()))
                .multiply(new BigDecimal(orderTO.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(orderTO.getOrderSn());
        itemEntity.setRealAmount(multiply);

        itemEntity.setSkuQuantity(orderTO.getNum());

        orderItemService.save(itemEntity);

    }


    /**
     * 保存订单数据
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }


    /**
     * 创建订单
     *
     * @return
     */
    private OrderCreateTo createOrder() {
        //订单号
        String orderSn = IdWorker.getTimeId();
        // 返回对象
        OrderCreateTo createTo = new OrderCreateTo();

        // 1、构建订单主表
        OrderEntity orderEntity = buildOrder(orderSn);

        // 2、订单项数据准备
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);


        //3、计算价格、积分等相关
        computePrice(orderEntity, itemEntities);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);

        return createTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");

        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        //订单的总额，叠加每一个订单项的总额信息
        for (OrderItemEntity entity : itemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
//            Integer growth = entity.getGiftGrowth();
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));

        }
        //1、订单价格相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        //设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);//未删除


    }

    private OrderEntity buildOrder(String orderSn) {
        OrderEntity entity = new OrderEntity();

        OrderSubmitVO submitVo = confirmVoThreadLocal.get();
        // 1、订单表数据准备
        // 1.1、订单号
        entity.setOrderSn(orderSn);
        // 1.2、获取收货信息
        R r = wareFeignService.getFare(submitVo.getAddrId());
        FareVO fareResp = r.getData(new TypeReference<FareVO>() {
        });
        // 1.3、运费金额
        entity.setFreightAmount(fareResp.getFare());
        // 1.4、收货人信息
        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());
        // 1.5、会员信息
        MemberRespVO respVo = LoginUserInterceptor.loginUser.get();
        entity.setMemberId(respVo.getId());
        //设置订单的相关状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);

        return entity;
    }

    /**
     * 将购物车里的所有购物项转化为订单详情的购物项
     *
     * @param
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //重要！！！ 这个接口最后确认查询sku的价格,用户最后支付的价格就是以这个接口查询的价格支付
        List<OrderItemVO> currentUserCartItems = cartFeignService.getCurrentUserCartItems();

        if (!CollectionUtils.isEmpty(currentUserCartItems)) {
            List<OrderItemEntity> collect = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return collect;
        }

        return null;
    }

    /**
     * 将购物车的购物项转化为orderItem表的订单项
     *
     * @param cartItem 购物车的一个购物项
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVO cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();

        // 1、订单信息

        // 2、商品的spu信息

        R r = productFeignService.getSpuInfoBySkuId(cartItem.getSkuId().toString());
        SpuInfoVO spuInfoVO = r.getData(new TypeReference<SpuInfoVO>() {
        });
        orderItemEntity.setSpuId(spuInfoVO.getId());
        orderItemEntity.setSpuBrand(spuInfoVO.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfoVO.getSpuName());
        orderItemEntity.setCategoryId(spuInfoVO.getCatalogId());
        // 3、商品的sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        // 4、优惠信息 todo v1.0版本不引入优惠券功能, 后续版本可能引入

        // 5、积分信息 todo 积分应该与skuInfo有关,v1.0版本不做处理
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //6、订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额。 总额-各种优惠
        BigDecimal orign = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }

}